<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="版本号" prop="cfversion">
        <el-input
          v-model="queryParams.cfversion"
          placeholder="请输入编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="类别名称" prop="fname">
        <el-input
          v-model="queryParams.fname"
          placeholder="请输入类别"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最新版" prop="cfisnew">
        <el-select v-model="queryParams.cfisnew" placeholder="请选择是否最新版" clearable>
          <el-option
            v-for="dict in dict.type.yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="时间类型" prop="cfseasontypeid" >
        <el-select v-model="queryParams.cfseasontypeid" placeholder="请选择时间类型" clearable>
          <el-option
            v-for="dict in dict.type.bom_seasontype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="基地" prop="cfwfzbaseid">
        <el-select v-model="queryParams.cfwfzbaseid" placeholder="请选择基地" clearable>
          <el-option
            v-for="dict in dict.type.bom_wfzbase"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bomcostestimation/basedocument:coefficient:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bomcostestimation/basedocument:coefficient:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bomcostestimation/basedocument:coefficient:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bomcostestimation/basedocument:coefficient:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-download" plain size="mini" @click="importTemplate">下载导入模板
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain size="mini" @click="importExcelsettlementrateentry">导入数据
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading"  border stripe :data="coefficientList"
              max-height="800px" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="版本号" align="center" prop="cfversion" width="180"/>
      <el-table-column label="类别" align="center" prop="fnumber" />
      <el-table-column label="类别名称" align="center" prop="fname" />
      <el-table-column label="最新版" align="center" prop="cfisnew"  >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.yes_no" :value="scope.row.cfisnew"/>
        </template>
      </el-table-column>
      <el-table-column label="车间" align="center" prop="cfplantid"  >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bom_plant" :value="scope.row.cfplantid"/>
        </template>
      </el-table-column>
      <el-table-column label="时间类型" align="center" prop="cfseasontypeid"  >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bom_seasontype" :value="scope.row.cfseasontypeid"/>
        </template>
      </el-table-column>
      <el-table-column label="基地" align="center" prop="cfwfzbaseid"  >
        <template slot-scope="scope">
          <dict-tag :options="dict.type.bom_wfzbase" :value="scope.row.cfwfzbaseid"/>
        </template>
      </el-table-column>
      <el-table-column label="人工变动(工序)" align="center" prop="cfrgbd" />
      <el-table-column label="人工固定(共耗)" align="center" prop="cfrggd" />
      <el-table-column label="水变动(直接)" align="center" prop="cfsbd" />
      <el-table-column label="水固定(共耗)" align="center" prop="cfsgd" />
      <el-table-column label="电变动(直接)" align="center" prop="cfdbd" />
      <el-table-column label="电固定(共耗)" align="center" prop="cfdgd" />
      <el-table-column label="气变动(直接)" align="center" prop="cfqbd" />
      <el-table-column label="气固定(共耗)" align="center" prop="cfqgd" />
      <el-table-column label="折旧变动(直接)" align="center" prop="cfzjbd" />
      <el-table-column label="折旧固定(共耗)" align="center" prop="cfzjgd" />
      <el-table-column label="其他变动(直接)" align="center" prop="cfqtbd" />
      <el-table-column label="其他固定(共耗)" align="center" prop="cfqtgd" />
      <el-table-column label="额定额" align="center" prop="cfede" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bomcostestimation/basedocument:coefficient:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bomcostestimation/basedocument:coefficient:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改系数对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title"  v-drag :visible.sync="open" width="1500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="8">
            <el-form-item label="版本号" prop="cfversion">
              <el-input v-model="form.cfversion" placeholder="请输入版本号" disabled/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类别" prop="fnumber">
              <el-input v-model="form.fnumber" placeholder="请选择类别" readonly/>
              <span class="el-input__suffix">
                <span class="el-input__suffix-inner">
                  <i class="el-input_icon icon el-icon-search"
                     onmousemove="this.style.color='#366EDD'"
                     onmouseout="this.style.color='#919191'"
                     style="font-size: 16px;
                            position: absolute;
                            cursor: pointer;
                            right: 6px;
                            top: 8px;
                            background-color: #ffffff;"
                     @click="openF7('category',false,null)"
                  />
                </span>
              </span>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="类别名称" prop="fname">
              <el-input v-model="form.fname" placeholder="请输入名称" disabled/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="时间类型" prop="cfseasontypeid">
              <el-select v-model="form.cfseasontypeid" placeholder="请选择时间类型" style="width: 366.67px" @change="changeSelection('seasontype')" clearable>
                <el-option
                  v-for="dict in dict.type.bom_seasontype"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="车间" prop="cfplantid">
              <el-select v-model="form.cfplantid" placeholder="请选择车间"  style="width: 366.67px" disabled clearable>
                <el-option
                  v-for="dict in dict.type.bom_plant"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="基地" prop="cfwfzbaseid">
              <el-select v-model="form.cfwfzbaseid" placeholder="请选择基地" style="width: 366.67px" @change="changeSelection('wfzbase')"  clearable>
                <el-option
                  v-for="dict in dict.type.bom_wfzbase"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="人工变动(工序)" prop="cfrgbd">
              <el-input v-model="form.cfrgbd" placeholder="请输入人工变动(工序)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水变动(直接)" prop="cfsbd">
              <el-input v-model="form.cfsbd" placeholder="请输入水变动(直接)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电变动(直接)" prop="cfdbd">
              <el-input v-model="form.cfdbd" placeholder="请输入电变动(直接)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="人工固定(共耗)" prop="cfrggd">
              <el-input v-model="form.cfrggd" placeholder="请输入人工固定(共耗)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="水固定(共耗)" prop="cfsgd">
              <el-input v-model="form.cfsgd" placeholder="请输入水固定(共耗)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="电固定(共耗)" prop="cfdgd">
              <el-input v-model="form.cfdgd" placeholder="请输入电固定(共耗)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="气变动(直接)" prop="cfqbd">
              <el-input v-model="form.cfqbd" placeholder="请输入气变动(直接)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折旧变动(直接)" prop="cfzjbd">
              <el-input v-model="form.cfzjbd" placeholder="请输入折旧变动(直接)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他变动(直接)" prop="cfqtbd">
              <el-input v-model="form.cfqtbd" placeholder="请输入其他变动(直接)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="气固定(共耗)" prop="cfqgd">
              <el-input v-model="form.cfqgd" placeholder="请输入气固定(共耗)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="折旧固定(共耗)" prop="cfzjgd">
              <el-input v-model="form.cfzjgd" placeholder="请输入折旧固定(共耗)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="其他固定(共耗)" prop="cfqtgd">
              <el-input v-model="form.cfqtgd" placeholder="请输入其他固定(共耗)"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="额定额" prop="cfede">
              <el-input v-model="form.cfede" placeholder="请输入额定额"
                        onkeyup="this.value=this.value.match(/\d+\.?\d{0,6}/);"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最新版" prop="cfisnew">
              <el-select v-model="form.cfisnew" placeholder="请选择是否最新版" style="width: 366.67px" disabled clearable>
                <el-option
                  v-for="dict in dict.type.yes_no"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="备注" prop="cfmemo">
              <el-input v-model="form.cfmemo" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <base-data-view @emitToParent="getF7Data" :tobasedata.sync='basedatadialog'></base-data-view>
    <el-dialog :title="excels.excelEntry.title" :visible.sync="excels.excelEntry.show" width="400px">
      <template v-show="excels.excelEntry.show">
        <div>
          <div class="container">
            {{ excels.excelEntry.upload_file || "导入" }}
            <input
              type="file"
              accept=".xls,.xlsx"
              class="upload_file"
              :value="excels.excelEntry.data"
              @change="readExcelsettlementrateentry($event)"
            />
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { listCoefficient, getCoefficient, delCoefficient, addCoefficient, updateCoefficient,importData } from "@/api/bomcostestimation/basedocument/coefficient";
import baseDataView from "@/views/bomcostestimation/f7View/baseDataView";
import * as XLSX1 from "xlsx";

export default {
  name: "Coefficient",
  dicts: ['bill_state','bom_wfzbase','bom_seasontype','bom_plant','yes_no'],
  components: {
    "baseDataView": baseDataView
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      numbers: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 系数表格数据
      coefficientList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //excel导入模板参数
      excels: {
        excelEntry: {
          show: false,
          excelList:[],
          upload_file: "",
          data: ""
        },
      },
      //F7数据对话框数据
      basedatadialog: {
        //定义一个参数用来存储当前需要修改的行数（存在分录的情况下）
        tempTableRowIndex: null,
        //定义一个参数用来判断当前是获取什么类型的数据
        F7dataType: null,
        wfzbase: {
          show: false
        },
        category: {
          show: false
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        cfversion: null,
        fnumber: null,
        fname: null,
        cfisnew: null,
        cfplantid: null,
        cfseasontypeid: null,
        cfwfzbaseid: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fnumber: [
          { required: true, message: "类别不能为空", trigger: "blur" }
        ],
        cfwfzbaseid: [
          { required: true, message: "基地不能为空", trigger: "blur" }
        ],
        cfseasontypeid: [
          { required: true, message: "时间类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询系数列表 */
    getList() {
      this.loading = true;
      listCoefficient(this.queryParams).then(response => {
        this.coefficientList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fid: null,
        fname: null,
        fnumber: null,
        fdescription: null,
        fsimplename: null,
        fcreatorid: null,
        fcreatetime: null,
        flastupdateuserid: null,
        flastupdatetime: null,
        cfplantid: null,
        cfcategory: null,
        cfcategoryname: null,
        cfchangefee: null,
        cffixationfee: null,
        cfavgcoefficient: null,
        cfmemo: null,
        cfstarttime: null,
        cfendtime: null,
        cfseasontypeid: null,
        cfversion: null,
        cfisnew: null,
        cfrgbd: null,
        cfrggd: null,
        cfsbd: null,
        cfsgd: null,
        cfdbd: null,
        cfdgd: null,
        cfqbd: null,
        cfqgd: null,
        cfzjbd: null,
        cfzjgd: null,
        cfqtbd: null,
        cfqtgd: null,
        cfede: null,
        cfwfzbaseid: null,
        f7wfzbaseNumber: null,
        f7wfzbaseName: null,
        f7wfzbaseShow: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fid)
      this.numbers = selection.map(item => item.cfversion)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加系数";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fid = row.fid || this.ids
      getCoefficient(fid).then(response => {
        this.form = response.data;
        if(this.form.cfisnew!=null){
          this.form.cfisnew = this.form.cfisnew+"";
        }
        this.open = true;
        this.title = "修改系数";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fid != null) {
            updateCoefficient(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoefficient(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fids = row.fid || this.ids;
      const numbers = row.cfversion || this.numbers;
      this.$modal.confirm('是否确认删除系数编号为"' + numbers + '"的数据项？').then(function() {
        return delCoefficient(fids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bomcostestimation/basedocument/coefficient/export', {
        ...this.queryParams
      }, `coefficient_${new Date().getTime()}.xlsx`)
    },
    //下载分录模板
    importTemplate() {
      this.download('bomcostestimation/basedocument/coefficient/importTemplate', {}, `系数导入模板_${new Date().getTime()}.xlsx`)
    },
    // 点击进行导入
    importExcelsettlementrateentry() {
      this.excels.excelEntry.upload_file = "";
      this.excels.excelEntry.data = "";
      this.excels.excelEntry.show = true;
    },
    //解析导入的excel文件
    readExcelsettlementrateentry(e) {
      // 读取表格文件
      let that = this;
      const files = e.target.files;
      if (files.length <= 0) {
        return false;
      } else if (!/\.(xls|xlsx)$/.test(files[0].name.toLowerCase())) {
        this.$message({
          message: "上传格式不正确，请上传xls或者xlsx格式",
          type: "warning"
        });
        return false;
      } else {
        // 更新获取文件名
        that.excels.excelEntry.upload_file = files[0].name;
      }
      const fileReader = new FileReader();
      fileReader.onload = ev => {
        try {
          const data = ev.target.result;
          const workbook = XLSX1.read(data, {
            type: "binary"
          });
          const wsname = workbook.SheetNames[0]; //取第一张表
          const ws = XLSX1.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
          // 从解析出来的数据中提取相应的数据
          that.excels.excelEntry.excelList = [];
          ws.forEach(item => {
            that.excels.excelEntry.excelList.push({
              fnumber: item["类别"],
              fname: item["类别名称"],
              cfseasontypeid: item["时间类型"],
              cfplantid: item["车间"],
              cfwfzbaseid: item["基地"],
              cfrgbd: item["人工变动(工序)"],
              cfrggd: item["人工固定(共耗)"],
              cfsbd: item["水变动(直接)"],
              cfsgd: item["水固定(共耗)"],
              cfdbd: item["电变动(直接)"],
              cfdgd: item["电固定(共耗)"],
              cfqbd: item["气变动(直接)"],
              cfqgd: item["气固定(共耗)"],
              cfzjbd: item["折旧变动(直接)"],
              cfzjgd: item["折旧固定(共耗)"],
              cfqtbd: item["其他变动(直接)"],
              cfqtgd: item["其他固定(共耗)"],
              cfede: item["额定额"],
              cfmemo: item["备注"],
            });
          });
          importData(that.excels.excelEntry.excelList).then(response => {
            this.open = false;
            this.getList();
            this.$modal.msgWarning("后台导入中");
          })
          // 结束解析动画
          this.excels.excelEntry.show = false;
        } catch (e) {
          return false;
        }
      };
      fileReader.readAsBinaryString(files[0]);
    },
    changeSelection(type){
      if(type=="wfzbase"){
        this.$refs["form"].validateField("cfwfzbaseid");
      }else{
        this.$refs["form"].validateField("cfseasontypeid");
      }
    },
    /** f7点击事件 */
    openF7(show) {
      debugger
      this.basedatadialog.F7dataType = show;
      switch (show) {
        case 'wfzbase':
          this.basedatadialog.wfzbase.show = !this.basedatadialog.wfzbase.show;
          break;
        case 'category':
          this.basedatadialog.category.show = !this.basedatadialog.category.show;
          break;
      }
    },
    /** f7获取值 */
    getF7Data(data) {
      debugger
      switch (this.basedatadialog.F7dataType) {
        case "wfzbase":
          if (data.wfzbase != null) {
            this.form.f7wfzbaseNumber = data.wfzbase.fnumber;
            this.form.cfwfzbaseid = data.wfzbase.fid;
            this.form.f7wfzbaseName = data.wfzbase.fname;
            this.form.f7wfzbaseShow = data.wfzbase.fname;
          }
          break;
        case "category":
          if (data.category != null) {
            this.form.cfcategory = data.category.id;
            this.form.fnumber = data.category.number;
            this.form.fname = data.category.name;
            this.form.cfplantid = data.category.cfplantid;
          }
          this.$refs["form"].validateField("fnumber");
          break;
      }
    }
    ,
  }
};
</script>
